<template>
  <div class="history-view">
    <el-card class="history-card">
      <template #header>
        <div class="card-header">
          <h2>生成历史</h2>
          <p class="subtitle">查看您的表情包生成记录</p>
        </div>
      </template>

      <el-empty v-if="!history.length" description="暂无生成记录"></el-empty>

      <el-timeline v-else>
        <el-timeline-item
          v-for="item in history"
          :key="item.history_id"
          :timestamp="formatDate(item.created_at)"
          placement="top"
        >
          <el-card class="history-item">
            <div class="history-content">
              <div class="history-info">
                <h4>{{ item.prompt_text }}</h4>
                <p>风格：{{ getStyleName(item.style) }}</p>
              </div>
              <div class="history-image">
                <el-image 
                  :src="getFullImageUrl(item.output_url)"
                  fit="contain"
                  :preview-src-list="[getFullImageUrl(item.output_url)]"
                ></el-image>
              </div>
              <div class="action-buttons">
                <el-button type="success" size="small" @click="downloadImage(item)">
                  <el-icon><Download /></el-icon> 下载
                </el-button>
                <el-button type="info" size="small" @click="copyLink(item)">
                  <el-icon><Link /></el-icon> 复制链接
                </el-button>
                <el-button type="primary" size="small" @click="shareEmoji(item)">
                  <el-icon><Share /></el-icon> 分享
                </el-button>
              </div>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>

      <div class="pagination-container" v-if="history.length">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="prev, pager, next"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Download, Link, Share } from '@element-plus/icons-vue'
import axios from 'axios'

const API_BASE_URL = 'http://localhost:5000'
const history = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const styleNames = {
  'cartoon': '卡通',
  'realistic': '写实',
  'funny': '搞笑',
  'cute': '可爱',
  'pixel': '像素',
  'watercolor': '水彩',
  'sketch': '素描',
  'anime': '动漫'
}

const getStyleName = (style) => {
  return styleNames[style] || style
}

const formatDate = (date) => {
  return new Date(date).toLocaleString('zh-CN')
}

const getFullImageUrl = (url) => {
  if (!url) return ''
  return url.startsWith('http') ? url : `${API_BASE_URL}${url}`
}

const loadHistory = async () => {
  try {
    const userId = localStorage.getItem('userId')
    if (!userId) {
      ElMessage.warning('请先登录')
      return
    }

    const response = await axios.get(`${API_BASE_URL}/api/history/${userId}`)
    if (response.data.status === 'success') {
      history.value = response.data.history
      total.value = response.data.total || history.value.length
    }
  } catch (error) {
    ElMessage.error('加载历史记录失败：' + (error.response?.data?.message || error.message))
  }
}

const handlePageChange = (page) => {
  currentPage.value = page
  loadHistory()
}

const downloadImage = (item) => {
  if (item?.output_url) {
    const link = document.createElement('a')
    link.href = getFullImageUrl(item.output_url)
    link.download = `emoji-${Date.now()}.${item.output_url.endsWith('.gif') ? 'gif' : 'png'}`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
}

const copyLink = (item) => {
  if (item?.output_url) {
    navigator.clipboard.writeText(getFullImageUrl(item.output_url))
    ElMessage.success('链接已复制')
  }
}

const shareEmoji = async (item) => {
  try {
    const response = await axios.post(`${API_BASE_URL}/api/share/${item.history_id}`)
    if (response.data.status === 'success') {
      ElMessage.success('分享成功，链接已复制到剪贴板')
      navigator.clipboard.writeText(response.data.share_url)
    }
  } catch (error) {
    ElMessage.error('分享失败：' + (error.response?.data?.message || error.message))
  }
}

onMounted(() => {
  loadHistory()
})
</script>

<style scoped>
.history-view {
  max-width: 1000px;
  margin: 0 auto;
}

.history-card {
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin-bottom: 8px;
  color: var(--primary-color);
}

.subtitle {
  color: var(--info-color);
  margin-top: 0;
}

.history-item {
  margin-bottom: 20px;
}

.history-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.history-info h4 {
  margin: 0;
  color: var(--text-color);
}

.history-info p {
  margin: 5px 0;
  color: var(--info-color);
}

.history-image {
  width: 100%;
  max-height: 200px;
  display: flex;
  justify-content: center;
}

.el-image {
  max-width: 100%;
  max-height: 200px;
  object-fit: contain;
  border-radius: 4px;
}

.action-buttons {
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>